﻿using System;

using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Net;


namespace ScrumFactory.Services.Web {

    public partial class MemberImage : System.Web.UI.Page {

        private ITeamService teamService = null;
        private ITeamService TeamService {
            get {
                if (teamService != null)
                    return teamService;                                
                teamService = ScrumFactory.Services.Web.Application.CompositionContainer.GetExportedValueOrDefault<ITeamService>();
                

                return teamService;
            }
            
        }

        private byte[] GetNullImage() {
            System.IO.FileStream fs = System.IO.File.OpenRead(Server.MapPath("Images/whoMember.png"));
            byte[] image = new byte[fs.Length];
            fs.Read(image, 0, image.Length);
            fs.Close();
            return image;
        }

        private byte[] GetDefaultImage() {
            System.IO.FileStream fs = System.IO.File.OpenRead(Server.MapPath("Images/noneMember.png"));
            byte[] image = new byte[fs.Length];
            fs.Read(image, 0, image.Length);
            fs.Close();
            return image;
        }

        private byte[] GetContactImage() {
            System.IO.FileStream fs = System.IO.File.OpenRead(Server.MapPath("Images/contactMember.png"));
            byte[] image = new byte[fs.Length];
            fs.Read(image, 0, image.Length);
            fs.Close();
            return image;
        }

        private byte[] GetGravatarImage(string email) {

            try {
                string hash = HashEmailForGravatar(email);
                string url  = string.Format("http://www.gravatar.com/avatar/{0}?default=404", hash);
                
                var webClient = new WebClient();
                                
                return webClient.DownloadData(url);

            } catch(Exception ex) {

                //System.IO.FileStream fstream = new System.IO.FileStream(Server.MapPath("~/App_Data/log.txt"), System.IO.FileMode.Append);

                //System.IO.StreamWriter writer = new System.IO.StreamWriter(fstream);
                //writer.WriteLine(DateTime.Now);
                //writer.WriteLine("GET AVATAR:" + ex.Message);
                //if(ex.InnerException!=null)
                //    writer.WriteLine(ex.InnerException.Message);
                //writer.WriteLine("------------------------------------------------------------------------------");
                //writer.Close();

                return new byte[0];
            }
        }

        private byte[] GetImage(string memberUId) {
            
            if (String.IsNullOrEmpty(memberUId)) 
                return GetNullImage();

            if(TeamService==null)
                return GetDefaultImage();

            MemberProfile member = TeamService.GetMember(memberUId);
            if(member==null) 
                return GetDefaultImage();

            if (member.IsContactMember)
                return GetContactImage();
           
            MemberAvatar avatar = TeamService.GetMemberAvatar(memberUId);
            if (avatar != null)
                return avatar.AvatarImage;

            byte[] gravatar = GetGravatarImage(member.EmailAccount);
            if (gravatar.Length != 0)
                return gravatar;

            return GetDefaultImage();
        }

        public static string HashEmailForGravatar(string email) {
            // Create a new instance of the MD5CryptoServiceProvider object.  
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.  
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(email));

            // Create a new Stringbuilder to collect the bytes  
            // and create a string.  
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data  
            // and format each one as a hexadecimal string.  
            for(int i = 0; i < data.Length; i++)
                sBuilder.Append(data[i].ToString("x2"));

            return sBuilder.ToString();  // Return the hexadecimal string. 
        }

        protected void Page_Load(object sender, EventArgs e) {
                        
            string memberUId = Request["memberUId"];

            byte[] image = GetImage(memberUId);

            Response.ContentType = "image/png";
            Response.BinaryWrite(image);

        }
    }
}